package com.s7.compat;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.s7.compat.manager.AppManager;

public abstract class CompatActivity extends AppCompatActivity {

    protected String LOG_TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getInstance().add(this);
    }

    @Override
    public void onBackPressed() {
        AppManager.getInstance().remove(this);
        super.onBackPressed();
    }

    public Bundle getBundle() {
        Bundle bundle = getIntent().getBundleExtra("bundle");
        return bundle;
    }

    public void onLoadingAnim() {

    }

    protected void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    protected void startActivity(Class<?> cls, Bundle bundle) {
        onLoadingAnim();
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtra("bundle", bundle);
        }
        startActivity(intent);
    }
    protected void startActivityForResult(Class<?> cls, int sign) {
        onLoadingAnim();
        Intent intent = new Intent();
        intent.setClass(this, cls);
        startActivityForResult(intent, sign);
    }

    protected void startActivityForResult(Class<?> cls, int sign, Bundle bundle) {
        onLoadingAnim();
        Intent intent = new Intent();
        intent.setClass(this, cls);
        intent.putExtra("bundle", bundle);
        startActivityForResult(intent, sign);
    }

    public Boolean hideInputMethod(View v) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            return imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
        return false;
    }


    public boolean isShouldHideInput(View view, MotionEvent event) {
        if(view != null && (view instanceof EditText)) {
            int[] leftTop = {0, 0};
            view.getLocationInWindow(leftTop);
            int left = leftTop[0],
                    top = leftTop[1],
                    bottom = top + view.getHeight(),
                    right = left + view.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public void finish() {
        AppManager.getInstance().remove(this);
        super.finish();
    }

    protected void onExit() {
        AppManager.getInstance().AppExit(this);
    }

}
